﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using HtmlAgilityPack;

namespace DBAItemCrawler
{
    public class NewestItem : INewestItem
    {
        public string HelloWorld()
        {
            return "Hello World!";
        }

        public List<Listing> GetListings(string address)
        {
            HtmlWeb web = new HtmlWeb();
            web.OverrideEncoding = Encoding.ASCII;
            HtmlDocument dom = web.Load("http://www.dba.dk/biltilbehoer/tilbehoer-og-reservedele/faelge-med-daek-og-tilbehoer/stoerrelsefaelge-17/?soeg=114");
            IEnumerable<HtmlNode> listingsEnum = dom.DocumentNode.Descendants("tr").Where(node => node.Attributes["class"] != null).Where(node => node.Attributes["class"].Value.Contains("dbaListing listing"));

            List<Listing> listings = new List<Listing>();
            foreach (HtmlNode listing in listingsEnum)
            {
                IEnumerable<HtmlNode> details = listing.Elements("td");
                string text = GetListingText(details.Where(node => node.Attributes["class"] != null).Where(node => node.Attributes["class"].Value.Contains("mainContent")).First());
                string link = GetListingLink(details.Where(node => node.Attributes["class"] != null).Where(node => node.Attributes["class"].Value.Contains("mainContent")).First());
                string city = GetListingCity(details.Where(node => node.Attributes["class"] != null).Where(node => node.Attributes["class"].Value.Contains("mainContent")).First());
                string date = GetListingDate(details.Where(node => node.Attributes["title"] != null).Where(node => node.Attributes["title"].Value.Contains("Dato")).First());
                string price = GetListingPrice(details.Where(node => node.Attributes["title"] != null).Where(node => node.Attributes["title"].Value.Contains("Pris")).First());
                listings.Add(new Listing(text, link, city, date, price));
            }

            return listings;
        }

        #region Retrieve listing details methods
        private string GetListingText(HtmlNode node)
        {
            return Utilities.GetCleanText(node.Element("a").Elements("span").ElementAt(1).InnerText);
        }

        private string GetListingLink(HtmlNode node)
        {
            return node.Element("a").Attributes["href"].Value;
        }

        private string GetListingCity(HtmlNode node)
        {
            return Utilities.GetCleanText(node.Element("ul").Elements("li").ElementAt(1).Element("span").Element("a").InnerText);
        }

        private string GetListingDate(HtmlNode node)
        {
            return Utilities.GetCleanText(node.InnerText);
        }

        private string GetListingPrice(HtmlNode node)
        {
            return Utilities.GetCleanText(node.InnerText);
        }
        #endregion
    }
}
